package com.birdboot.http;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

//该类的每一个实例用于表示浏览器发送过来的一个HTTP请求
public class HttpServletRequest {
    private Socket socket;
    private  String method;
    private  String uri;
    private String protocol;
    private Map<String,String> headers=new HashMap<>();
    public HttpServletRequest(Socket socket) throws IOException {
        this.socket=socket;
        //1.解析请求
        //1.1解析请求行
        String line=readLine();
        System.out.println("请求行："+line);
        String[] data=line.split("\\s");
        method=data[0];
        uri=data[1];
        protocol=data[2];

        System.out.println("mehtod:"+method);
        System.out.println("uri:"+uri);
        System.out.println("protocol:"+protocol);
        //1.2解析消息头
        //消息头相关信息 key:消息头名字 value:消息头对应的值

        while (true){
            line=readLine();
            if(line.isEmpty()){
                break;
            }
            System.out.println("消息头："+line);
            data=line.split(":\\s");
            headers.put(data[0],data[1]);
        }
        System.out.println("消息头："+headers);
    }
    private String readLine() throws IOException {
        InputStream in=socket.getInputStream();
        int d;
        char pre='a',cur='a';//pre表示上次读取的字符，cur表示本次读取的字符
        StringBuilder builder=new StringBuilder();
        while ((d=in.read())!=-1){
            cur=(char) d;
            if(pre==13&&cur==10){
                break;
            }
            builder.append(cur);
            pre=cur;
        }
        return builder.toString().trim();
    }

    public String getMethod() {
        return method;
    }

    public String getUri() {
        return uri;
    }

    public String getProtocol() {
        return protocol;
    }
    public String getHeader(String name){
        return headers.get(name);
    }

    public Map<String, String> getHeaders() {
        return headers;
    }
}

